package cn.com.xuhx.testMapper;

import cn.com.xuhx.mapper.CacheMapper;
import cn.com.xuhx.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

/**
 * myBatis缓存
 */
public class CacheTest {

    private SqlSession sqlSession = null;

    @Before
    public void getSQLSession() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //设置需要手动提交事务
        //sqlSession = build.openSession();
        //设置自动提交事务
        sqlSession = build.openSession(true);
    }

    @After
    public void closeSQLSession(){
        sqlSession.clearCache();
        sqlSession.close();
    }

    /**
     * 测试一级缓存(级别：sqlSession)
     * mybatis默认开启的就是一级缓存
     * 一级缓存失效的四种情况
     *  - 不是同一个sqlSession对象
     *  - 查询条件不同
     *  - 两次查询期间有做过任意增删改的情况
     *  - 手动清空了缓存 sqlSession.clearCache();
     */
    @Test
    public void testFirstCache(){
        CacheMapper mapper = sqlSession.getMapper(CacheMapper.class);
        User user = mapper.queryUserByID(7);
        System.out.println(user);

        CacheMapper mapper1 = sqlSession.getMapper(CacheMapper.class);
        User user2 = mapper1.queryUserByID(7);
        System.out.println(user2);
    }

    /**
     * 测试二级缓存（级别：sqlSessionFactory）（运行时注掉before和after）
     * 二级缓存生效的必要条件
     *  - 在核心配置文件中，设置全局配置属性<setting name="cacheEnabled" value="true" />，默认是true，所以不需要设置
     *  - 在mapper映射文件中设置标签<cache />
     *  - 二级缓存生效必须在SqlSession关闭或提交之后
     *  - 查询数据所转化的实体类必须实现序列化接口
     *  - 属于同一个sqlSessionFactory
     *  - 增删改也会使二级缓存失效
     * @throws IOException
     */
    @Test
    public void testSecondCache() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);

        SqlSession sqlSession1 = sqlSessionFactory.openSession(true);
        CacheMapper mapper1 = sqlSession1.getMapper(CacheMapper.class);
        User user1 = mapper1.queryUserByID(7);
        System.out.println(user1);
        sqlSession1.close();

        SqlSession sqlSession2 = sqlSessionFactory.openSession(true);
        CacheMapper mapper2 = sqlSession2.getMapper(CacheMapper.class);
        User user2 = mapper2.queryUserByID(7);
        System.out.println(user2);
        sqlSession2.close();
    }

    /**
     *
     * myBatis缓存查询顺序
     *  先查询二级缓存，二级缓存没有再查询一级缓存，一级缓存也没有就查询数据库
     */
}
